﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Configuration;
using System.Data;
using System.Diagnostics;
using System.IO;
using System.IO.Ports;
using System.Linq;
using System.Net.Http.Formatting;
using System.ServiceProcess;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Web.Http;
using System.Web.Http.Cors;
using System.Web.Http.SelfHost;

namespace ZK.YCGLRD_WindowsService
{

    public partial class Service1 : ServiceBase
    {
        private HttpSelfHostServer _server;
        private readonly HttpSelfHostConfiguration _config;
        public static readonly string ServiceAddress = Common.AppConfigHelper.GetAppSettings("ApiAddress");

        public static HardWareHelp.MHSNReader mHSNReader;
        public Service1()
        {
            InitializeComponent();

            //Common.DelegateHelper.MW_102N_MessageReceivedEvent += aa;

            _config = new HttpSelfHostConfiguration(ServiceAddress);
            _config.EnableCors(new EnableCorsAttribute("*", "*", "*"));
            _config.Formatters.JsonFormatter.MediaTypeMappings.Add(
                 new QueryStringMapping("datatype", "json", "application/json"));
            _config.Formatters.XmlFormatter.SupportedMediaTypes.Clear();
            _config.Routes.MapHttpRoute("DefaultApi",
                "api/{controller}/{action}/{id}",
                new { id = RouteParameter.Optional });
        }

        //private void aa(string carNum)
        //{
        //    ReaderController.cardNum = carNum;
        //}

        protected override void OnStart(string[] args)
        {
            try
            {
                _server = new HttpSelfHostServer(_config);
                _server.OpenAsync();
                //Common.Log4.LogManage.WriteInfo("初始化室内读卡器");
                //mHSNReader = new HardWareHelp.MHSNReader(Common.AppConfigHelper.GetAppSettings("ReaderPort"));

                Common.Log4.LogManage.WriteInfo("打开服务");
            }
            catch (Exception ex)
            {

                Common.Log4.LogManage.WriteErr("打开服务异常 " + ex.ToString());
            }

        }

        protected override void OnStop()
        {
            _server.CloseAsync().Wait();
            _server.Dispose();

            mHSNReader.CloseRes();

            Common.Log4.LogManage.WriteInfo("停止服务");
        }

    }
}
